// components/UploadFiles.js
const APP = getApp();
const TAB_DATA = [
    {label:'图片',value:'image'},
    {label:'视频',value:'video'},
    {label:'音频',value:'audio'},
    {label:'文档',value:'document'},
];

Component({
    lifetimes: {
        attached: function() {
          // 在组件实例进入页面节点树时执行
          let tmpTabs = TAB_DATA.filter((item)=>{
                return this.data.uploadType.includes(item.value);
            });
            this.setData({
                uploadTabs:tmpTabs,
            });
            //【在data中设置回调方法】
            let _this = this;
            // 【读取附件】
            // 数据格式:
            // [
            //     {originalname:'abc.png', urlname:'http://www.a.com/storage/abc.png', pathname:'storage/abc.png', presentname:'asdiw23asdladiwej2.png', type:'image'},
            //     {originalname:'abc.png', urlname:'http://www.a.com/storage/abc.png', pathname:'storage/abc.png', presentname:'asdiw23asdladiwej2.png', type:'image'},
            // ]
            this.data.getUploadFiles = function(){
                let tmpFiles = [];
                for(let key in _this.data.fileObj){
                    tmpFiles = tmpFiles.concat(_this.data.fileObj[key]);
                }
                return tmpFiles;
            },
            // 【加载附件】一
            // 数据格式:
            // [
            //     {fileName:'abc.png', fileUrl:'http://www.a.com/storage/abc.png', filePath:'storage/abc.png', presentName:'asdiw23asdladiwej2.png', fileType:'image'},
            //     {fileName:'abc.png', fileUrl:'http://www.a.com/storage/abc.png', filePath:'storage/abc.png', presentName:'asdiw23asdladiwej2.png', fileType:'image'},
            // ]
            this.data.setUploadFiles = function(list){
                for(let item of list){
                    switch(item.fileType){
                        case 'image':
                            _this.data.fileObj.images.push({
                                originalname:item.fileName,
                                urlname:item.fileUrl,
                                pathname:item.filePath,
                                presentname:item.presentName,
                                type:'image',
                            });
                            break;
                        case 'video':
                            _this.data.fileObj.videos.push({
                                originalname:item.fileName,
                                urlname:item.fileUrl,
                                pathname:item.filePath,
                                presentname:item.presentName,
                                type:'video',
                            });
                            break;
                        case 'audio':
                            _this.data.fileObj.audios.push({
                                originalname:item.fileName,
                                urlname:item.fileUrl,
                                pathname:item.filePath,
                                presentname:item.presentName,
                                type:'audio',
                            });
                            break;
                        case 'document':
                            _this.data.fileObj.documents.push({
                                originalname:item.fileName,
                                urlname:item.fileUrl,
                                pathname:item.filePath,
                                presentname:item.presentName,
                                type:'document',
                            });
                            break;
                    }
                }
                //Tabs标签设置
                let tmpTabs = TAB_DATA.filter((item)=>{
                    item.num = _this.data.fileObj[item.value+'s'].length;
                    return _this.data.uploadType.includes(item.value);
                });
                _this.setData({
                    uploadTabs:tmpTabs,
                    ['fileObj.images']:_this.data.fileObj.images,
                    ['fileObj.videos']:_this.data.fileObj.videos,
                    ['fileObj.audios']:_this.data.fileObj.audios,
                    ['fileObj.documents']:_this.data.fileObj.documents,
                });
            }

            // 【加载附件】二
            this.data.setUploadFileObj = function(fileObj){
                if(null == fileObj) return;
                
                _this.data.fileObj.images = fileObj.images;
                _this.data.fileObj.videos = fileObj.videos;
                _this.data.fileObj.audios = fileObj.audios;
                _this.data.fileObj.documents = fileObj.documents;

               //Tabs标签设置
               let tmpTabs = TAB_DATA.filter((item)=>{
                    item.num = _this.data.fileObj[item.value+'s'].length;
                    return _this.data.uploadType.includes(item.value);
                });
                _this.setData({
                    uploadTabs:tmpTabs,
                    ['fileObj.images']:_this.data.fileObj.images,
                    ['fileObj.videos']:_this.data.fileObj.videos,
                    ['fileObj.audios']:_this.data.fileObj.audios,
                    ['fileObj.documents']:_this.data.fileObj.documents,
                });
            }

            //绑定事件：bindSynchUploadReffer
            this.triggerEvent('SynchUploadReffer',this); //【注意】事件名称区分大小写
        },
        detached: function() {
          // 在组件实例被从页面节点树移除时执行
          for(let filepath of this.data.tmpDownloadFilePath){
            //同步清除预览的缓存文件
            APP.apptool.unlinkDocument(filepath);
          }
        },
    },
    /**
     * 组件的属性列表
     */
    properties: {
        //附件列表
        fileObj:{
            type:Object,
            value:{images:[],videos:[],audios:[],documents:[]},
        },
        //上传文件大小（单位MB）
        maxFileSize:{
            type:Number,
            value:1,
        },
        //上传数量限制
        maxFileNum:{
            type:Number,
            value:8,
        },
        //上传类型
        uploadType:{
            type:Array,
            // value:['image','video','audio','document']
            value:['image','video','document']
        },
        //默认上传
        defaultType:{
            type:String,
            value:'image',
        },
        //默认索引
        uploadIndex:{
            type:Number,
            value:0,
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        uploadTabs:[],
        uploadTimeout: 10*60*1000, //10分钟（单位：毫秒）
        tmpDownloadFilePath:[],//临时缓存路径
        isUploading:false, //上传进行中标识
    },

    /**
     * 组件的方法列表
     */
    methods: {
        //预览
        bindPreview(e){
            let _this = this;
            let dataset = e.currentTarget.dataset;
            if(this.data.defaultType == 'image'){
                wx.previewImage({
                    current: dataset.src, // 当前显示图片的 http 链接
                    urls: _this.data.fileObj.images.map((currentValue, index,arr)=>{
                        return currentValue.urlname;
                    }), // 需要预览的图片 http 链接列表
                  });
            }else if(this.data.defaultType == 'video'){
                wx.previewMedia({                  
                    current:dataset.idx,
                    sources: _this.data.fileObj.videos.map((currentValue, index,arr)=>{
                        return {url:currentValue.urlname,type:'video',poster:''};
                    }),
                });
            }else if(this.data.defaultType == 'audio'){
                //无需预览
            }else if(this.data.defaultType == 'document'){
                APP.apptool.openDocument(_this.data.fileObj.documents[dataset.idx].urlname,function(tempFilePath){
                    _this.data.tmpDownloadFilePath.push(tempFilePath);
                });
            }
        },
        //上传类型
        bindTabChange(e){
            if(this.data.isUploading) return;
            this.setData({
                defaultType:e.detail.value
            });
        },
        //上传文件
        bindUpload(e) {
            switch(this.data.defaultType){
                case 'image':
                    this.doUploadImage();
                    break;
                case 'video':
                    this.doUploadVideo();
                    break;
                 case 'audio':
                    target = '音频';
                    break;
                case 'document':
                    this.doUploadFile();
                    break;
            }
        },
        //删除文件
        bindDel(e) {
            let _this = this;
            let dataset = e.currentTarget.dataset;
            let target = '图片';
            switch(this.data.defaultType){
                case 'image':
                    target = '图片';
                    break;
                case 'video':
                    target = '视频';
                    break;
                 case 'audio':
                    target = '音频';
                    break;
                case 'document':
                    target = '文档';
                    break;
            }
            APP.apptool.showModalConfirm('提示', '确认删除该'+target+'？', '放弃', '确认',function(confirm, cancel){
                if(cancel) return;
                if(_this.data.defaultType == 'image'){
                    _this.data.fileObj.images.splice(dataset.idx,1);
                    _this.setData({
                        ['fileObj.images']:_this.data.fileObj.images
                    },function(){
                        APP.apptool.showToastInfo('删除成功!');
                    });
                }else if(_this.data.defaultType == 'video'){
                    _this.data.fileObj.videos.splice(dataset.idx,1);
                    _this.setData({
                        ['fileObj.videos']:_this.data.fileObj.videos
                    },function(){
                        APP.apptool.showToastInfo('删除成功!');
                    });
                }else if(_this.data.defaultType == 'audio'){
                    _this.data.fileObj.audios.splice(dataset.idx,1);
                    _this.setData({
                        ['fileObj.audios']:_this.data.fileObj.audios
                    },function(){
                        APP.apptool.showToastInfo('删除成功!');
                    });
                }else if(_this.data.defaultType == 'document'){
                    _this.data.fileObj.documents.splice(dataset.idx,1);
                    _this.setData({
                        ['fileObj.documents']:_this.data.fileObj.documents
                    },function(){
                        APP.apptool.showToastInfo('删除成功!');
                    });
                }
            });
        },
        //检测文件大小
        doCheckFileSize(fileSize){
            if(fileSize > this.data.maxFileSize*1024*1024){
                APP.apptool.showModalInfo('上传的附件必须小于 '+ this.data.maxFileSize + ' MB');
                return false;
            }
            return true;
        },
        //检测文件扩展名
        doCheckFileExtention(fileExtention,fileExtentions){
            if(fileExtentions.includes(fileExtention)){
                APP.apptool.showModalInfo('仅支持上传'+fileExtentions.join('、')+'的附件');
                return false;
            }
            return true;
        },
        //获取扩展名
        doGetFileExtention(filepath){
            if(-1 == filepath.lastIndexOf('.')) return '';
            return filepath.trim().toLocaleLowerCase().substring(filepath.lastIndexOf('.'));
        },
        //上传附件
        doUpload(filePath,realname){
            let _this = this;

            //过滤上传中
            if(this.data.isUploading) return;

            let authInfo = APP.appauth.getAuthInfo();
            if (authInfo) {
                 //头部
                let headers = {
                    'token':authInfo.userToken,
                };

                const tmpRealName = realname;
                const uploadTask = wx.uploadFile({
                    url: APP._weburl('/Upload/file'),
                    filePath: filePath,
                    name: 'file',
                    header:headers,
                    formData: {
                        fileType:_this.data.defaultType,
                        token:authInfo.userToken
                    },
                    timeout:_this.data.uploadTimeout, //（单位：毫秒）
                    success(res) {
                        APP.applog.debug(res);
                        if (res.statusCode !== 200) {
                            APP.apptool.showModalInfo('网络请求错误');
                            return;
                        }
                        if (typeof res.data !== 'string') {
                            APP.apptool.showModalInfo('响应数据错误');
                            return;
                        }
                        let resData = JSON.parse(res.data);
                        if(resData.caCode == APP.appconfig.fwcode.successed){
                            for(let file of resData.caData){
                                //附件类型，逗号分隔1 图片2视频3文件
                                if(_this.data.defaultType == 'image'){
                                    _this.data.fileObj.images.push({
                                        originalname:file.originalName,
                                        urlname:file.fileUrl,
                                        pathname:file.filePath,
                                        presentname:file.presentName,
                                        type:'image',
                                    });
                                    _this.setData({
                                        ['fileObj.images']:_this.data.fileObj.images
                                    },function(){
                                        _this.doUploadFinish();
                                    });
                                }else if(_this.data.defaultType == 'video'){
                                    _this.data.fileObj.videos.push({
                                        originalname:file.originalName,
                                        urlname:file.fileUrl,
                                        pathname:file.filePath,
                                        presentname:file.presentName,
                                        type:'video',
                                    });
                                    _this.setData({
                                        ['fileObj.videos']:_this.data.fileObj.videos
                                    },function(){
                                        _this.doUploadFinish();
                                    });
                                }else if(_this.data.defaultType == 'audio'){
                                    _this.data.fileObj.audios.push({
                                        originalname:file.originalName,
                                        urlname:file.fileUrl,
                                        pathname:file.filePath,
                                        presentname:file.presentName,
                                        type:'audio',
                                    });
                                    _this.setData({
                                        ['fileObj.audios']:_this.data.fileObj.audios
                                    },function(){
                                        _this.doUploadFinish();
                                    });
                                }else if(_this.data.defaultType == 'document'){
                                    _this.data.fileObj.documents.push({
                                        // originalname:tmpRealName,
                                        originalname:file.originalName,
                                        urlname:file.fileUrl,
                                        pathname:file.filePath,
                                        presentname:file.presentName,
                                        type:'document',
                                    });
                                    _this.setData({
                                        ['fileObj.documents']:_this.data.fileObj.documents
                                    },function(){
                                        _this.doUploadFinish();
                                    });
                                }
                            }
                        }else{
                            APP.apptool.showToastInfo(resData.msg);
                        }
                    },
                    fail(res) {
                        APP.applog.error(res);
                    },
                    complete(res) {
                        // setTimeout(()=>{
                        //     _this.setData({
                        //         isUploading:false,
                        //     });
                        // },1500);
                    },
                });
                //进度监听
                uploadTask.onProgressUpdate((res)=>{
                    // console.log('上传进度', res.progress);
                    // console.log('已经上传的数据长度', res.totalBytesSent);
                    // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend);

                    if(!_this.data.isUploading){
                        _this.data.isUploading = true;
                        _this.setData({
                            isUploading:true,
                        });
                    }
                    wx.showLoading({
                      title: '上传'+res.progress+'%',
                    });
                    if(res.progress==100){
                        wx.hideLoading();
                        // _this.setData({
                        //     isUploading:false
                        // });
                    }
                });
            }
        },
        //强制完成
        doUploadFinish(){
            this.setData({
                isUploading:false
            });
            wx.hideLoading();
        },
        //上传文件
        doUploadFile(){
            let _this = this;
            wx.chooseMessageFile({
                count: 1,
                type:'file',
                extension: ['doc','xls','ppt','pdf','docx','xlsx','pptx','txt','rtf','rar','zip'],
                success(res) {
                    APP.applog.info(res);
                    let tempFile = res.tempFiles[0];
                    // //检测文件
                    // if(!_this.doCheckFileExtention(_this.doGetFileExtention(tempFile.path),['doc','xls','ppt','pdf','docx','xlsx','pptx','txt','rtf','rar','zip'])) return;
                    //检测大小
                    if(!_this.doCheckFileSize(tempFile.size)) return;
                    //上传文件
                    _this.doUpload(tempFile.path,tempFile.name);
                },
                fail(err){
                    APP.applog.error(err);
                }
            });
        },
        //上传视频
        doUploadVideo(){
            let _this = this;
            wx.chooseMedia({
                count: 1,
                mediaType:['video'],
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                maxDuration: 60,//单位
                success(res) {
                    APP.applog.info(res);
                    let tempFile = res.tempFiles[0];
                    //检测文件
                    if(!_this.doCheckFileExtention(_this.doGetFileExtention(tempFile.tempFilePath),['mp4','mov','ogv','avi'])) return;
                    //检测大小
                    if(!_this.doCheckFileSize(tempFile.size)) return;
                    //上传文件
                    _this.doUpload(tempFile.tempFilePath,'');
                },
                fail(err){
                    APP.applog.error(err);
                }
            });
        },
        //上传图片
        doUploadImage(){
            let _this = this;
            wx.chooseMedia({
                count: 1,
                mediaType:['image'],
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    APP.applog.info(res);
                    let tempFile = res.tempFiles[0];
                    //检测文件
                    if(!_this.doCheckFileExtention(_this.doGetFileExtention(tempFile.tempFilePath),['jpg','jpeg','png'])) return;
                    //检测大小
                    if(!_this.doCheckFileSize(tempFile.size)) return;
                    //上传文件
                    _this.doUpload(tempFile.tempFilePath,'');
                },
                fail(err){
                    APP.applog.error(err);
                }
            });
        },
        //同步数据
        doSynchData(){
            //绑定事件属性： bindSynchUploadReffer
            let _this = this;
            this.triggerEvent('SynchUploadReffer',{_this}); //【注意】事件名称区分大小写
        },
    },
})
